import pandas as pd
from sklearn.metrics import mean_squared_error
import torch
import onnx
import onnxruntime
import numpy as np

# Load PyTorch model
model = torch.load('predict price.pth')
test_data = pd.read_csv('test.csv', header=None)
test_tensor = torch.tensor(test_data.values, dtype=torch.float32)
np.savetxt('out.csv', model(test_tensor).detach().numpy(), fmt='%f', delimiter=',')
# Create a dummy input with the same shape as the actual input
dummy_input = torch.randn(1, 331)

# Export the model to ONNX format
torch.onnx.export(model, dummy_input, 'predict price.onnx')

# Load the ONNX model
onnx_model = onnx.load('predict price.onnx')

# Check the model's correctness
onnx.checker.check_model(onnx_model)


# Load the ONNX model
onnx_session = onnxruntime.InferenceSession('predict price.onnx', providers=['CPUExecutionProvider'])

# Get the input and output namesimport numpy as np
input_name = onnx_session.get_inputs()[0].name
output_name = onnx_session.get_outputs()[0].name

# Make predictions on the test dataset
predictions = []
for i in range(len(test_data)):
    # Get the input data
    input_data = test_data.iloc[i].values.reshape(1, -1).astype('float32')
    
    # Run the model
    output = onnx_session.run([output_name], {input_name: input_data})[0]
    
    # Get the prediction
    prediction = output[0]
    predictions.append(prediction)

# Convert the predictions list to a pandas DataFrame
predictions_df = pd.DataFrame(predictions, columns=['prediction'])

# Save the DataFrame to a CSV file
predictions_df.to_csv('predictions.csv', index=False)

# Read the original output file
out_df = pd.read_csv('out.csv', header=None)

# Read the ONNX model output file
predictions_df = pd.read_csv('predictions.csv', header=None)

# Drop the first row of predictions_df
predictions_df = predictions_df.iloc[1:]

# Calculate the mean squared error
mse = mean_squared_error(out_df, predictions_df)

# Print the mean squared error
print(mse)